package slash.client;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.logging.Logger;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

import slash.client.controllers.GameController;
import slash.game.Game;
import slash.client.swing.controls.GamePanel;

public class Slash {

	  private static Logger logger = Logger.getLogger(Slash.class.getName());

	  private static JFrame mainWindow;

	  private static void createAndShowGui() {
	    mainWindow = new JFrame("Slash");
	    mainWindow.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
	    mainWindow.addWindowListener(new WindowAdapter() {
	      public void windowClosing(WindowEvent e) {
	        if (GameController.get().canExit()) {
	          mainWindow.dispose();
	        }
	      }
	    });
	    mainWindow.getContentPane().add(new GamePanel(GameController.get().getGame()));
	    mainWindow.setJMenuBar(createMenuBar());
	    mainWindow.pack();

	    // Center the new window on the desktop
	    Toolkit toolkit = Toolkit.getDefaultToolkit();
	    Dimension screenSize = toolkit.getScreenSize();
	    int x = (screenSize.width - mainWindow.getWidth()) / 2;
	    int y = (screenSize.height - mainWindow.getHeight()) / 2;
	    mainWindow.setLocation(x, y);

	    mainWindow.setVisible(true);
	  }

	  private static JMenuBar createMenuBar() {
	    JMenuBar menuBar = new JMenuBar();
	    JMenu fileMenu = new JMenu("File");
	    fileMenu.setMnemonic(KeyEvent.VK_F);
	    menuBar.add(fileMenu);

	    JMenuItem saveItem = new JMenuItem("Save", KeyEvent.VK_S);
	    saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
	    saveItem.addActionListener(new ActionListener() {
	      public void actionPerformed(ActionEvent e) {
	        GameController.get().saveGame();
	      }
	    });
	    fileMenu.add(saveItem);

	    fileMenu.addSeparator();
	    
	    JMenuItem exitItem = new JMenuItem("Exit", KeyEvent.VK_X);
	    exitItem.addActionListener(new ActionListener() {
	      public void actionPerformed(ActionEvent e) {
	        mainWindow.setVisible(false);
	        mainWindow.dispose();
	      }
	    });
	    fileMenu.add(exitItem);

	    return menuBar;
	  }

	  public static void main(String... args) {
	    logger.entering(Slash.class.getName(), "main");
	    SwingUtilities.invokeLater(new Runnable() {
	      public void run() {
	        createAndShowGui();
	        GameController.get().fireStart();
	      }
	    });
	    logger.exiting(Slash.class.getName(), "main");
	  }
}
